package com.gs.disk.service.common;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gs.common.exception.RenException;
import com.gs.disk.dao.admin.UserDao;
import com.gs.disk.dao.common.MenuDao;
import com.gs.entity.MenuEntity;
import com.gs.entity.UserEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;

@Service
@Slf4j
public class MenuService {

    @Resource
    private MenuDao menuDao;

    @Resource
    private UserDao userDao;

    /**
     * 获取菜单树形结构
     * @return
     */
    public List<MenuEntity> listTree() {
        List<MenuEntity> menuEntities = menuDao.listTree();

        return menuEntities;
    }

    /**
     * 根据用户信息获取用户菜单
     * @param userId 用户id
     * @return
     */
    public List<MenuEntity> userMenu(Long userId) {
        AtomicReference<List<MenuEntity>> result = new AtomicReference<>(new LinkedList<>());
        UserEntity userEntity = userDao.selectById(userId);

        // 用户有哪些权限(菜单)
        Optional<String> permissions = Optional.ofNullable(userEntity.getPermissions());
        permissions.ifPresent(value -> {
            // 获取圣旨
            log.info("圣旨", value);

            String[] permissionArr = value.split(",");

            List<MenuEntity> menuEntities = menuDao.listUserMenuTree(permissionArr, false);
            result.set(menuEntities);
        });
        permissions.orElseGet(() -> {

            // 获取职权
            return null;
        });

        return result.get();
    }

    public void saveMenu(MenuEntity menuEntity) {

        // 一级菜单初始化
        if(menuEntity.getParentId() == null) {
            menuEntity.setMenuLevel(1);
            menuEntity.setComponent("LAYOUT");
        } else {
            // 判断菜单层级
            // ...
            menuEntity.setMenuLevel(2);
            // component = 上级path + / + 下级path
            MenuEntity parentMenuEntity = menuDao.selectById(menuEntity.getParentId());
            String component = String.format("%s/%s", parentMenuEntity.getPath(), menuEntity.getPath());
            menuEntity.setComponent(component);

            // 1582395600353787905	user/user	用户管理	sys:user:list,sys:user:info,sys:user:delete,sys:user:update,sys:user:add	/system/user/user			0	2	5	1	2022-10-18 23:38:05
        }

        menuDao.insertOrUpdate(menuEntity);
    }

    /**
     * 删除菜单
     * @param id 菜单id
     */
    public void deleteMenu(Long id) {
        QueryWrapper<MenuEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);
        Integer count = menuDao.selectCount(wrapper);
        if(count > 1) {
            throw new RenException("请先删除下级菜单");
        }
        menuDao.deleteById(id);
    }
}
